package com.sh4.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sh4.util.HttpUtil;
import com.sh4.util.KMTUtil;
import com.sh4.util.Sh4Utils;
import com.sh4.websocket.WebSocketService;
import com.sh4.wxservice.ClientService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


@Controller
@RequestMapping(value="system",method=RequestMethod.POST)
public class MainController {
	
//	@Autowired
//	private RedisTemplate<String, String> redisTemplate;
//	
	
	@RequestMapping(value = "main")
	@ResponseBody
	public Map<String,String> main(){
		Map<String , String> map = new HashMap<String, String>();
//		try {
//			WebSocketDemo.SendMessageTone("登录成功！", "client001");
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		map.put("hello", "world");  
		return map;
	}
	
	@RequestMapping(value = "templateMessageTest")
	@ResponseBody
	public JSONObject templateMessageTest(@RequestBody JSONObject reqBody){
		
		
		return ClientService.MSTemplate(reqBody.getString("openId"), reqBody.getString("nickname"), reqBody.getString("orderDate"),reqBody.getString("address"), reqBody.getString("remark"), Sh4Utils.getAccess_token());
	}
	
	@RequestMapping(value = "resourceSearch")
	@ResponseBody
	public Map<String,Object> mainAoxiang(@RequestBody JSONObject reqBody){
		Map<String , Object> map = new HashMap<String, Object>();
		ArrayList<Object> dList = new ArrayList<Object>();
		try {
			
			String [] ids = reqBody.getString("ids").split(",");
			
			for(String id : ids) {
				String url = "http://person.amac.org.cn/pages/login/resource!search.action?filter_EQS_APP_ID=" + id + "&sqlkey=homepage&sqlval=HONG_KAOSHI_SELECT";
				JSONArray json = JSONArray.fromObject(HttpUtil.doGet(url));
				ArrayList<Object> gList = new ArrayList<Object>();
				for(int i = 0 ; i < json.size() ; i++){
					JSONObject grade = json.getJSONObject(i);
					String testTime = grade.getString("SSG_EXAM_TIME");
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
					Date testDate = sdf.parse(testTime);
					String currentDateStr = sdf.format(new Date());
					String testDateStr = sdf.format(testDate);
					if(testDateStr.equals(currentDateStr) || "01".equals(grade.getString("SSG_IS_PASS"))) {
						gList.add(grade);
					}
				}
				Map<String , Object> m = new HashMap<String , Object>();
				m.put(id, gList);
				dList.add(m);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println(e.toString());
		}
		map.put("dataList", dList);
		return map;
	}
	
	
	@RequestMapping(value = "axiosTest")
	@ResponseBody
	public Map<String,Object> axiosTest(){
		Map<String , Object> map = new HashMap<String, Object>();
		
		List<Map<String , String>> dataList = new ArrayList<Map<String , String>>();
		
		Map<String , String> m1 = new HashMap<String , String>();
		m1.put("url", "http://bbsfiles.vivo.com.cn/vivobbs/attachment/forum/201710/03/204231mfew33efpps7pu5i.jpg");
		m1.put("key", "1");
		Map<String , String> m2 = new HashMap<String , String>();
		m2.put("url", "http://bbsfiles.vivo.com.cn/vivobbs/attachment/forum/201710/03/204231mfew33efpps7pu5i.jpg");
		m1.put("key", "2");
		dataList.add(m1);
		dataList.add(m2);
		map.put("pics", dataList);  
		return map;
	}
	
	@RequestMapping(value = "initScoket")
	@ResponseBody
	public Map<String,Object> initScoket(HttpSession session){
		Map<String , Object> map = new HashMap<String, Object>();
		if(session.getAttribute("userCode") != null) {
			map.put("status", 200);  
		}else {
			map.put("status", 300);
		}
		return map;
	}
	
	@RequestMapping(value = "linsterwx" , method = RequestMethod.POST)
	@ResponseBody
	public Map<String,String> linsterwx(@RequestParam String openId){
		Map<String , String> map = new HashMap<String, String>();
		try {
			WebSocketService.SendMessageTone(openId, "client001");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		map.put("hello", "world");  
		return map;
	}
	
	
	@RequestMapping(value = "getticketscanback")
	@ResponseBody
    public void getTicket(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		ServletInputStream inputStream = request.getInputStream();
        ServletOutputStream outputStream = response.getOutputStream(); 
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");

        //首次请求申请验证,返回echostr
        if(echostr!=null){
        	KMTUtil.outputStreamWrite(outputStream,echostr);
            return;
        }

        //验证请求签名
//        if(!signature.equals(SignatureUtil.generateEventMessageSignature(TOKEN,timestamp,nonce))){
//            System.out.println("The request signature is invalid");
//            return;
//        }
        
        boolean isreturn= false;
        System.out.print("1.收到微信服务器消息");
        Map<String, String> wxdata = KMTUtil.parseXml(request);
        System.out.print(wxdata.toString());
        System.out.print(wxdata.toString());
        if(wxdata.get("MsgType")!=null){
            if("event".equals(wxdata.get("MsgType"))){
            	System.out.print("2.1解析消息内容为：事件推送");
                if( "subscribe".equals(wxdata.get("Event"))){
                	System.out.print("2.2用户第一次关注 返回true哦");
                    isreturn=true;
                }
            }
        }
        WebSocketService.SendMessageTone("登录成功！", "client001");
        System.out.print("3.0 默认登录成功！");
	}
}
